package com.butterfly.hotkey.worker.framework.netty.server;

import cn.hutool.core.util.StrUtil;
import com.butterfly.hotkey.core.constant.Constants;
import com.butterfly.hotkey.core.model.msg.HotKeyMsg;
import com.butterfly.hotkey.core.util.FastJsonUtil;
import com.butterfly.hotkey.common.factory.CommonFactory;
import com.butterfly.hotkey.common.netty.INettyMsgHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.butterfly.hotkey.core.constant.MsgTypeConst.REMOVE_APP;
import static com.butterfly.hotkey.worker.constants.FactoryConstant.HANDLER;

/**
 * Worker的handler
 *
 * @author butterfly
 */
public class WorkerChannelHandler extends SimpleChannelInboundHandler<String> {

    private static final Logger log = LoggerFactory.getLogger(Constants.WORKER);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx,
                                String message) throws Exception {
        if (StrUtil.isBlank(message)) {
            return;
        }
        // 处理各类消息
        HotKeyMsg hotKeyMsg = FastJsonUtil.parseObject(message, HotKeyMsg.class);
        byte msgType = hotKeyMsg.getMsgType();
        INettyMsgHandler handler = CommonFactory.getBean(HANDLER, msgType);
        if (handler == null) {
            return;
        }
        handler.handle(hotKeyMsg, ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("client channel in active:{}", ctx.name());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("client channel in inactive:{}", ctx.name());

        INettyMsgHandler workerHandler = CommonFactory.getBean(HANDLER, REMOVE_APP);
        if (workerHandler != null) {
            workerHandler.handle(null, ctx);
        }
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("[hotkey-worker] some thing is error ", cause);
    }
}
